
import os
import sys
from pathlib import Path


CODE_DIR = Path(__file__).parent.parent / 'code'
sys.path.insert(0, str(CODE_DIR))

from mp3_json_enhanced import transcribe_audio_to_json, ENHANCED_MODE_AVAILABLE, HUBERT_MODE_AVAILABLE
from translation_module import translate_text
from qwen_polish_module import polish_text
from tts_module import text_to_speech


class TranslationService:

    def __init__(self):
        self.data_dir = Path(__file__).parent.parent / '数据'
        self.transcript_dir = self.data_dir / 'Jason转录数据'
        self.audio_output_dir = self.data_dir / '翻译结果'


        self.transcript_dir.mkdir(parents=True, exist_ok=True)
        self.audio_output_dir.mkdir(parents=True, exist_ok=True)

    def process_audio(self, audio_path, direction='fr2zh', mode=1):
        result = {
            'original_text': '',
            'translated_text': '',
            'polished_text': '',
            'audio_path': '',
            'transcription_details': {},
            'usage': {
                'xunfei_chars': 0,
                'qwen_tokens': 0
            }
        }


        if direction == 'zh2fr':
            source_lang = 'zh'
            target_lang = 'fr'
            translate_direction = 'chinese_to_french'
        else:
            source_lang = 'fr'
            target_lang = 'zh'
            translate_direction = 'french_to_chinese'

        try:

            print(f"📝 步骤1: 转录音频（模式{mode}）...")

            use_enhanced = (mode == 2) and ENHANCED_MODE_AVAILABLE
            use_hubert = (mode == 3) and HUBERT_MODE_AVAILABLE

            json_filepath = transcribe_audio_to_json(
                audio_path=audio_path,
                model_size='small',
                output_dir=str(self.transcript_dir),
                use_enhanced_mode=use_enhanced,
                use_hubert_mode=use_hubert,
                source_language=source_lang
            )


            import json
            with open(json_filepath, 'r', encoding='utf-8') as f:
                transcript_data = json.load(f)


            original_text = transcript_data.get('text', '') or transcript_data.get('transcript', '')
            result['original_text'] = original_text
            result['transcription_details'] = transcript_data

            print(f"✓ 转录完成: {len(original_text)} 字符")
            print(f"   内容: {original_text[:100]}...")

            if not original_text:
                print(f"⚠️  JSON内容: {transcript_data}")
                raise ValueError("转录结果为空")


            print(f"🌐 步骤2: 翻译文本（{translate_direction}）...")

            success, translated_text, trans_usage, error_msg = translate_text(
                text=original_text,
                direction=translate_direction
            )

            if not success:
                raise ValueError(f"翻译失败: {error_msg}")

            result['translated_text'] = translated_text
            result['usage']['xunfei_chars'] += trans_usage

            print(f"✓ 翻译完成: {len(translated_text)} 字符")


            print(f"🎨 步骤3: AI润色优化...")

            try:

                polish_language = 'chinese' if target_lang == 'zh' else 'french'

                success, polished_text, polish_usage, error_msg = polish_text(
                    text=translated_text,
                    target_language=polish_language
                )

                if success:
                    result['polished_text'] = polished_text
                    result['usage']['qwen_tokens'] += polish_usage
                    print(f"✓ 润色完成: {len(polished_text)} 字符")

                    final_text = polished_text
                else:
                    print(f"⚠️  润色失败（使用原翻译）: {error_msg}")
                    final_text = translated_text
                    result['polished_text'] = translated_text

            except Exception as e:
                print(f"⚠️  润色失败（使用原翻译）: {e}")
                final_text = translated_text
                result['polished_text'] = translated_text


            print(f"🔊 步骤4: 生成语音...")

            from datetime import datetime
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            output_audio_name = f'web_translated_{timestamp}.mp3'
            output_audio_path = self.audio_output_dir / output_audio_name


            tts_language = 'chinese' if target_lang == 'zh' else 'french'

            tts_success, tts_usage = text_to_speech(
                text=final_text,
                output_path=str(output_audio_path),
                language=tts_language
            )

            if not tts_success:
                print("⚠️  语音生成失败")


            result['audio_path'] = f'/api/audio/{output_audio_name}'
            result['usage']['xunfei_chars'] += tts_usage

            print(f"✓ 语音生成完成: {output_audio_path.name}")


            print(f"\n✅ 翻译完成！")
            print(f"   原文: {len(original_text)} 字符")
            print(f"   译文: {len(translated_text)} 字符")
            print(f"   润色: {len(result['polished_text'])} 字符")
            print(f"   讯飞API: {result['usage']['xunfei_chars']} 字符")
            print(f"   通义千问: {result['usage']['qwen_tokens']} tokens")

            return result

        except Exception as e:
            print(f"❌ 翻译服务错误: {e}")
            import traceback
            traceback.print_exc()
            raise


if __name__ == '__main__':

    print("="*70)
    print("🧪 翻译服务测试")
    print("="*70)

    service = TranslationService()


    test_audio = Path(__file__).parent.parent / '音频仓库' / '测试mp3（French）.mp3'

    if test_audio.exists():
        print(f"\n📁 测试音频: {test_audio.name}")
        print(f"   大小: {test_audio.stat().st_size / 1024:.1f} KB")
        print()

        result = service.process_audio(
            audio_path=str(test_audio),
            direction='fr2zh',
            mode=1
        )

        print("\n" + "="*70)
        print("📊 测试结果")
        print("="*70)
        print(f"原文: {result['original_text'][:100]}...")
        print(f"译文: {result['translated_text'][:100]}...")
        print(f"润色: {result['polished_text'][:100]}...")
        print(f"音频: {result['audio_path']}")
        print("="*70)
    else:
        print(f"❌ 测试音频不存在: {test_audio}")
